import 'dart:developer';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/widght/image_widget.dart';
import 'package:laos_mall/models/home/home_model.dart';
import 'package:laos_mall/pages/main/catergory/product_detail/view.dart';
import 'package:laos_mall/pages/main/home/logic.dart';

class FlipListView extends StatefulWidget {
  FlipListView({Key? key, this.pageController, this.swiperCtl,this.images})
      : super(key: key);
  final PageController? pageController;
  final PageController? swiperCtl;
  final List<Products>? images;
  @override
  _FlipListViewState createState() => _FlipListViewState();
}

class _FlipListViewState extends State<FlipListView>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
   List<Products> images = [];
  late PageController pageController;
  late PageController swiperCtl;
  double currentPage = 0.0; // 当前页面索引（带小数部分）
  bool swiperScroll = true;
  SwiperController swiperCtr = SwiperController();
  final logic = Get.find<HomeLogic>();
  final ScrollController scrollController = ScrollController();
  @override
  bool get wantKeepAlive => true; // 保持状态不被销毁
  @override
  void initState() {
    super.initState();
    pageController = widget.pageController ?? PageController();
    swiperCtl = widget.swiperCtl ?? PageController();

    // images = [{"img":"img1.jpeg","list":["img1.jpeg", "img2.jpeg", "img3.jpeg", "img4.jpeg"]},
    //   {"img":"img2.jpeg","list":["img1.jpeg", "img2.jpeg", "img3.jpeg", "img4.jpeg"]},
    //   {"img":"img2.jpeg","list":["img1.jpeg", "img2.jpeg", "img3.jpeg", "img4.jpeg"]},
    //   {"img":"img3.jpeg","list":["img1.jpeg", "img2.jpeg", "img3.jpeg", "img4.jpeg"]},
    // ];
    images = widget.images ?? [];

    pageController.addListener(() {
      setState(() {
        currentPage = pageController.page ?? 0.0; // 更新当前页面索引
      });
    });

    final logic = Get.find<HomeLogic>();
    var onlyOne = false;
    // swiperCtl.addListener(() {
    //   print("offset == ${swiperCtl.offset}  page == ${swiperCtl.page}");
    //
    //   if(swiperCtl.page ==  images.length - 1){
    //     // logic.tabCtl.animateTo(logic.tabCtl.index + 1);
    //     // setState(() {
    //     //   swiperScroll = false;
    //     // });
    //     if(logic.tabCtl.index < logic.categorys.length - 1){
    //       if(!onlyOne){
    //         logic.tabCtl.animateTo(logic.tabCtl.index + 1);
    //         onlyOne = true;
    //       }
    //     }
    //   }else if(swiperCtl.page == 0){
    //     // setState(() {
    //     //   swiperScroll = false;
    //     // });
    //     if(logic.tabCtl.index > 0){
    //       // if(!onlyOne){
    //         logic.tabCtl.animateTo(logic.tabCtl.index - 1);
    //         // onlyOne = true;
    //       // }
    //     }
    //   }
    // });


    var indexRight = 0;
    var indexLeft = 0;
    swiperCtl.addListener(() {
      // print("offset == ${swiperCtl.offset}  page == ${swiperCtl.page}");
      print(
          "swiperCtl.page == ${swiperCtl.page}  swiperCtl.offset == ${swiperCtl.offset}  index = ${logic.tabCtl.index}");

      // var isRight = swiperCtl.offset > 0 ? true : false;
      // int direct = swiperCtl.offset > 0
      //     ? 2
      //     : swiperCtl.offset < 0
      //         ? 0
      //         : 1;
      //
      // if (swiperCtl.page == images.length - 1 && isRight) {
      //   bool isFirstRun = false;
      //   if (logic.tabCtl.index + 1 > logic.categorys.length - 1) {
      //     return;
      //   }
      //   if (indexRight == 0) {
      //     indexLeft = 0;
      //     logic.tabCtl.animateTo(logic.tabCtl.index + 1);
      //     indexRight += 1;
      //   }
      // } else if (swiperCtl.page == 0 && !isRight) {
      //   if (logic.tabCtl.index - 1 < 0) {
      //     return;
      //   }
      //   if (indexLeft == 0) {
      //     indexRight = 0;
      //     logic.tabCtl.animateTo(logic.tabCtl.index - 1);
      //     indexLeft += 1;
      //   }
      // }

    });
  }

  @override
  void dispose() {
    pageController.dispose();
    swiperCtl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return PageView.builder(
      controller: pageController,
      itemCount: images.length,
      scrollDirection: Axis.vertical,
      itemBuilder: (context, index) {
        // 计算当前页面和下一个页面的动画值
        double offset = currentPage - index;
        int floorNum = currentPage.floor();
        int cellNum = currentPage.ceil();
        // print("当前页面 ${index} 上一页${floorNum}  下一页${cellNum} offset == ${offset}");
        double rotation = offset * 3.14 / 2; // 根据偏移量计算旋转角度

        return _buildItem(index, rotation, isTwo: cellNum == index);
        // return _buildPageItem(index, rotation, isTwo: cellNum == index);

        // if (floorNum == index || cellNum == index) {
        //   // return _buildPageItem(index, rotation, isTwo: cellNum == index);
        //   return _buildItem(index, rotation, isTwo: cellNum == index);
        // } else {
        //   // 其他页面保持静态
        //   return Image.asset(
        //     images[index].toImgPath(directory: 'test_img'),
        //     fit: BoxFit.cover,
        //   );
        // }
      },
    );
  }

  _buildItem(index, rotation, {bool isTwo = false, bool isDown = true}) {
    // return _buildPageItem(index, rotation);
     var imgs = images[index].images;
    return Swiper(
      itemBuilder: (context, subIndex) {
        return _buildAninationItem(index, subIndex,rotation,
            isTwo: isTwo, isDown: isDown);
      },
      itemCount: imgs.length,
      onIndexChanged: (itemIndex){
        // if(itemIndex == imgs.length - 1 && logic.tabCtl.index != logic.tabCtl.index - 1){
        //   logic.tabCtl.animateTo(logic.tabCtl.index + 1);
        // }else if(itemIndex == 0 && logic.tabCtl.index != 0){
        //   logic.tabCtl.animateTo(logic.tabCtl.index - 1);
        // }

      },
      onTap: (subIndex){
        print(images[index].product_id);
        Get.to(()=> ProductDetailPage(),arguments: {"id":images[index].product_id,"sku_id":images[index].sku_id});
      },
      loop: false,
      autoplay: false,
    );
  }

  _buildAninationItem(int index,int subIndex, rotation,
      {bool isTwo = false, bool isDown = true}) {
    var transform = Matrix4.identity()
      ..setEntry(3, 2, 0.0015)
      ..rotateX(-rotation);
    if (isTwo) {
      transform = Matrix4.identity()
        ..setEntry(3, 2, 0.0015)
        ..rotateX(-rotation);
    }
    var  item = images[index];
    return Transform(
        alignment: isTwo ? Alignment.topCenter : Alignment.bottomCenter,
        transform: transform, // 绕 X 轴旋转
        child: Stack(
          children: [
            Positioned.fill(
                child: ImageWidget(
                url: item.images[subIndex].pic_url,
              fit: BoxFit.cover,
            )),
            Positioned(left: 20.w,bottom: 20.w,right: 20.w,child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
              Text("${item.title}",style: TextStyle(color: Colors.white),),
              SizedBox(height: 18.w,),
              AppButton.sizeBtn(() {
                logic.jumpLogin(item);
              }, "ADD TO CART",style: AppButtonStyle.hollowWhite)
            ],).addContainer(color: Colors.transparent),)
          ],
        ));
  }

  _buildPageItem(index, rotation, {bool isTwo = false, bool isDown = true}) {
    var widget = PageView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, subIndex) {
        return _buildAninationItem(index,subIndex, rotation,
            isTwo: isTwo, isDown: isDown);
      },
      controller: swiperCtl,
      itemCount: images.length,
      physics: swiperScroll == true
          ? AlwaysScrollableScrollPhysics()
          : NeverScrollableScrollPhysics(),
    );
    return widget;
  }
}
